/**
 * 主页内容操作方法
 */

var userGlobal = {
};
layui.define(['jquery', 'request', 'table', 'treeTable', 'form', 'tools', 'layer', 'admin', 'permission'], function(exports) {
	var $ = layui.jquery;
	var table = layui.table;
	var treeTable = layui.treeTable;
	var form = layui.form;
	var tools = layui.tools;
	var layer = layui.layer;
	var admin = layui.admin;
	var permission = layui.permission;
	var MOD_NAME = 'content';

	var content = new function() {
		this.render = function() {
			initLayuiForm();
			//自动加载搜索功能
			$("body").on("click", "*[data-toggle='tableSearch']", function(event) {
				var $form = $(this).parents("form");
				var $table = $form.data("table") || $form.nextAll("table:first");
				var params = tools.arrayToJson($form.serializeArray());
				table.reloadData($table.attr("id"), { where: params, page: { curr: 1 } }, true);
				return false;
			});

			//自动跳转页面
			$("body").on("click", "*[data-toggle='page']", function(event) {
				var url = $(this).data('url');
				var title = $(this).data('title');
				var type = $(this).data('type');
				var start = $(this).data('start'); //是否追加页面
				if(start){
					admin.startPage(title, url,  type);
				}else{
					admin.toPage(title, url,  type);
				}
			});
			
			ajaxInterceptor();
		}

		this.initTableOptions = function(options) {
			var _this = this;
			var iniOptions = {
				cellMinWidth: 80,
				page: true,
				defaultToolbar: ['filter', 'exports', 'print'],
				autoSort: false,
				text: {
					none: '无数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
				},
				method: "post",
				contentType: "application/json;charset=UTF-8",
				headers: {
					"token": sessionStorage.getItem('token')
				},
				parseData: function(res) {
					return {
						'code': 0, //接口状态
						'msg': '', //提示文本
						'count': res.total, //数据长度
						'data': res.data //数据列表，是直接填充进表格中的数组
					}
				},
				request: { //当接口需要请求参数时，在这修改,属性名不能修改,只能更改参数
					pageName: 'page', //开始的页码的参数名称,newName是你接口需要的名字，默认：page
					limitName: 'size' //每页数据量的参数名,newNumber是你接口需要的名字，默认：limit
				},
				done: permission.validPerm,
			};
			$.extend(iniOptions, options);
			return iniOptions;
		}

		this.tableListener = function(tableInst) {
			var options = tableInst.config;
			if (options.layfilter) {
				table.on('toolbar(' + options.layfilter + ')', function(obj) {
					var checkStatus = table.checkStatus(options.id);
					var data = checkStatus.data;
					if (obj.event == "custom") {
						var handle = $(this).data("handle");
						if (handle) {
							var $callback = new Function("arg", "(" + handle + "(arg))");
							if ($callback) {
								$callback(data);
							}
						}
					}

				});
				//工具行监听
				table.on('tool(' + options.layfilter + ')', function(obj) {
					var data = obj.data;
					if (obj.event == "custom") {
						var handle = $(this).data("handle");
						if (handle) {
							var $callback = new Function("arg", "(" + handle + "(arg))");
							if ($callback) {
								$callback(data);
							}
						}
					}
				});
				//单选框事件
				table.on('radio(' + options.layfilter + ')', function(obj) {
					var data = obj.data;
					var handle = $(options.elem).data("radio")
					if (handle) {
						var $callback = new Function("arg", "(" + handle + "(arg))");
						if ($callback) {
							$callback(data);
						}
					}
				});
				// 行单击事件
				table.on('row(' + options.layfilter + ')', function(obj) {
					var data = obj.data; // 获取当前行数据
					// 标注当前点击行的选中状态
					obj.setRowChecked({
						type: 'radio' // radio 单选模式；checkbox 复选模式
					});
					var handle = $(options.elem).data("row")
					if (handle) {
						var $callback = new Function("arg", "(" + handle + "(arg))");
						if ($callback) {
							$callback(data);
						}
					}
				});
				//监听排序事件 
				table.on('sort(' + options.layfilter + ')', function(obj) {
					table.reloadData(options.id, {
						initSort: obj,//记录初始排序，如果不设的话，将无法标记表头的排序状态。
						where: {
							sort: obj.field, //排序字段
							order: obj.type //排序方式
						}
					}, true)
				});
			}
		}

		this.treeTableListener = function(tableInst) {
			var options = tableInst.config;
			if (options.layfilter) {
				treeTable.on('toolbar(' + options.layfilter + ')', function(obj) {
					var checkStatus = treeTable.checkStatus(options.id);
					var data = checkStatus.data;
					if (obj.event == "custom") {
						var handle = $(this).data("handle");
						if (handle) {
							var $callback = new Function("arg", "(" + handle + "(arg))");
							if ($callback) {
								$callback(data);
							}
						}
					}
				});
				//工具行监听
				treeTable.on('tool(' + options.layfilter + ')', function(obj) {
					var data = obj.data;
					if (obj.event == "custom") {
						var handle = $(this).data("handle");
						if (handle) {
							var $callback = new Function("arg", "(" + handle + "(arg))");
							if ($callback) {
								$callback(data);
							}
						}
					}
				});
				//单选框事件
				treeTable.on('radio(' + options.layfilter + ')', function(obj) {
					var data = obj.data;
					var handle = $(options.elem).data("radio")
					if (handle) {
						var $callback = new Function("arg", "(" + handle + "(arg))");
						if ($callback) {
							$callback(data);
						}
					}
				});
				// 行单击事件
				treeTable.on('row(' + options.layfilter + ')', function(obj) {
					var data = obj.data; // 获取当前行数据
					// 标注当前点击行的选中状态
					obj.setRowChecked({
						type: 'radio' // radio 单选模式；checkbox 复选模式
					});
					var handle = $(options.elem).data("row")
					if (handle) {
						var $callback = new Function("arg", "(" + handle + "(arg))");
						if ($callback) {
							$callback(data);
						}
					}
				});
				//监听排序事件 
				treeTable.on('sort(' + options.layfilter + ')', function(obj) {
					reloadTable(options.elem, {
						initSort: obj,//记录初始排序，如果不设的话，将无法标记表头的排序状态。
						where: {
							sort: obj.field, //排序字段
							order: obj.type //排序方式
						}
					});
				});

				//监听排序事件 
				table.on('sort(' + options.layfilter + ')', function(obj) {
					treeTable.reloadData(options.id, {
						initSort: obj,//记录初始排序，如果不设的话，将无法标记表头的排序状态。
						where: {
							sort: obj.field, //排序字段
							order: obj.type //排序方式
						}
					}, true)
				});
			}
		}

		this.initTable = function(options) {
			var iniOptions = this.initTableOptions();
			$.extend(iniOptions, options);
			var tableInst = table.render(iniOptions);
			this.tableListener(tableInst);
			return tableInst;
		}

		this.initTreeTable = function(options) {
			var iniOptions = this.initTableOptions();
			$.extend(iniOptions, options);
			var tableInst = treeTable.render(iniOptions);
			this.treeTableListener(tableInst);
			return tableInst;
		}

		this.reloadTable = function(id) {
			table.reloadData(id, null, true)
		}

		this.dialog = function(title, area, content) {
			return layer.open({
				type: 1,
				offset: '50px',
				title: title,
				area: area,
				content: content
			})
		}
		
		this.drawer = function(title, area, content,slide) {
			var slide= slide==null ? 'r' : slide;
			var anim ='slideLeft';
			switch(slide){
				case 't': anim="slideDown";break;
				case 'b': anim="slideUp";break;
				case 'l': anim="slideRight";break;
			}
			return layer.open({
				type: 1,
				offset: slide,
				anim: anim,
				title: title,
				area: area,
				content: content
			})
		}

		this.confirm = function(title, fn1, fn2) {
			layer.confirm(title, {
				offset: '50px',
				title: false,
				btn: ['确认', '取消'] //按钮
			}, fn1, fn2)
		}

		/**
		* 权限校验
		*/
		this.validPerm = function() {
			permission.validPerm();
		}

	};
	/**
* 初始化表单
 */
	function initLayuiForm() {
		form.set({
					autocomplete: 'off' // 阻止 input 框默认的自动输入完成功能
				});
		form.verify({
			length: function(value, item) {
				var minLen = $(item).data("minlen");
				var maxLen = $(item).data("maxlen");
				if (minLen && value.length < minLen) {
					return '最少' + minLen + '个字符';
				}
				if (maxLen && value.length > maxLen) {
					return '最多' + maxLen + '个字符';
				}
			},
			euqal: function(value, item) {
				var elemstr = $(item).data("relate");
				var tip = $(item).data("tip");
				var $equalElem;
				if (elemstr.indexOf("#") != 0) {
					$equalElem = $("*[name='" + elemstr + "']").first();
				} else {
					$equalElem = $(elemstr).val();
				}
				if (value != $equalElem.val()) {
					return tip || '两次输入不相同';
				}
			},
			noeuqal: function(value, item) {
				var elemstr = $(item).data("relate");
				var tip = $(item).data("tip");
				var $equalElem;
				if (elemstr.indexOf("#") != 0) {
					$equalElem = $("*[name='" + elemstr + "']").first();
				} else {
					$equalElem = $(elemstr).val();
				}
				if (value == $equalElem.val()) {
					return tip || '两次输入不能相同';
				}
			}
		});
	}
	
	function ajaxInterceptor(){
		$(document).ajaxSend(function (event, xhr, settings) {
		  // 修改请求参数
		 xhr.setRequestHeader('token', sessionStorage.getItem('token'));
		});
		
			// 响应成功后的拦截器
		$(document).ajaxSuccess(function (event, xhr, settings, data) {
		  // 修改响应数据
		  if(tools.isJSON(data)){
			  var json = JSON.parse(data);
			  switch(json.code){
				  case 3:
				  case 4:
					  sessionStorage.clear();
					  window.location.href = "/login.html";
					  break;
				  case 5:
					  admin.startPage("403", "view/exception/403.html", "_component");
			  }
		  }
		});		
		
		$(document).ajaxError(function(event,xhr,options,exc){
			if(xhr.status == 404){
				 admin.startPage("404", "view/exception/404.html", "_component");
			}else if(xhr.status == 500){
				 admin.startPage("500", "view/exception/500.html", "_component");
			}
		})

	}
	


	exports(MOD_NAME, content);
})